package com.sdk.springbootdynamicschedule.dynamictwo;

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Service
@Data
public class TaskService {
    @Autowired
    private ThreadPoolTaskScheduler scheduler;
    private Map<String, ScheduledFuture<?>> tasks = new ConcurrentHashMap<>();

    // 添加任务
    public void addTask(String taskId, String cron) {
        ScheduledFuture<?> future = scheduler.schedule(
                () -> System.out.println("动态任务执行"+taskId),
                new CronTrigger(cron)
        );
        tasks.put(taskId, future);
    }

    // 移除任务
    public void cancelTask(String taskId) {
        tasks.get(taskId).cancel(true);
    }
}
